window.addEventListener('load', function () {
    function initrender() {
        let id = location.search.slice(4)
        id && render(id)
        function render(id) {
            obj.url = '/my/article/' + id
            obj.type = 'get'
            obj.success = function (res) {
                //根据获取的数据渲染页面，表单赋值
                form.val("formTest", res.data)
                res.data.cate_id && renderSelect(res.data.cate_id)
                //渲染图片
                // renderImg(res.data.cover_img)
            }
            myAxios(obj)
        }
    }
    //渲染图片
    let cropper
    function renderImg(data) {
        let blob = new Blob([data])
        let imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
        image.src = imageUrl
        loadImg()
        //下步再处理
    }
    //渲染文章分类
    function renderSelect(cateId) {
        obj.type = 'get'
        obj.url = '/my/article/cates'
        obj.success = function (res) {
            let str = template('tpl-cate', res)
            str = str.replace(`value="${cateId}"`, `value="${cateId}" selected`)
            document.querySelector('select[name="cate_id"]').innerHTML = str
            form.render()
        }
        myAxios(obj)
    }
    let form = layui.form;
    layui.use('form', function () {
        initrender()
        //监听提交
        let cb = function (res) {
            console.log(res);
            if (res.status === 0) {
                // layer.msg(res.message, { time: 1000 })
                console.log(res.status);
            }
        }
        form.on('submit(formPub)', function (data) {
            obj.type = 'POST'
            obj.url = '/my/article/add'
            obj.upLoadFile = true
            obj.success = cb
            let formPub = document.querySelector('#form-pub')
            let formData = new FormData(formPub)
            cropper.getCroppedCanvas({
                height: 200,
                width: 200
            }).toBlob(function (blob) {
                formData.append('cover_img', blob)
                formData.append('state', '已发布')
                obj.data = formData
                myAxios(obj)
            })
            return false;
        });
        form.verify({
            morethan2: [
                /^[\S]{2,}$/
                , '最少包含2个字符'
            ]
        });
    });
    // 文章封面处理
    function loadImg() {
        cropper = new Cropper(image, {
            aspectRatio: 1,
            preview: '.img-preview'
        })
    }
    loadImg()
    btnChooseImage.onclick = function () {
        coverFile.click()
    }
    coverFile.onchange = function (e) {
        if (this.files.length === 0) return layer.msg('请选择图片', { time: 1000 })
        let imgUrl = URL.createObjectURL(this.files[0])
        cropper.replace(imgUrl)
    }
})